package com.lishuang.user.service.impl;

import com.lishuang.basic.constant.VerifyCodeConstants;
import com.lishuang.basic.exception.BusinessException;
import com.lishuang.basic.service.impl.BaseServiceImpl;
import com.lishuang.basic.util.MD5Utils;
import com.lishuang.basic.util.StrUtils;
import com.lishuang.user.domain.Logininfo;
import com.lishuang.user.domain.User;
import com.lishuang.user.dto.UserDto;
import com.lishuang.user.mapper.LogininfoMapper;
import com.lishuang.user.mapper.UserMapper;
import com.lishuang.user.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 用户手机注册
     *
     */
    @Override
    @Transactional
    public void phoneRegister(UserDto userDto) {

        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String pwd = userDto.getPwd();
        String confirmPwd = userDto.getConfirmPwd();

        //1.校验
        //1.1.空值校验
        if (StringUtils.isEmpty(phone)
                || StringUtils.isEmpty(phoneCode)
                || StringUtils.isEmpty(pwd)
                || StringUtils.isEmpty(confirmPwd)) {
            throw new BusinessException("数据不能为空!!!");
        }
        //1.2.两次密码是否相同
        if (!pwd.equals(confirmPwd)) {
            throw new BusinessException("两次密码不一致!!!");
        }
        //1.3.验证码是否过期
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_CODE_PREFIX + phone);
        if (obj == null) {
            throw new BusinessException("验证码已失效，请重新获取!!!");
        }
        //1.4.验证码是否正确  //  9527:1223555555
        String codeTmp = obj.toString().split(":")[0];
        if (!codeTmp.equalsIgnoreCase(phoneCode)) {
            throw new BusinessException("验证码错误!!!");
        }

        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);//自增
        //2.2.再保存t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);
    }

    /**
     * 用户邮箱注册
     *
     */
    @Override
    @Transactional
    public void emailRegister(UserDto userDto) throws MessagingException {
        String email = userDto.getEmail();
        String password = userDto.getPassword();
        String confirmPassword = userDto.getConfirmPassword();
        //1.1.空值校验
        if (StringUtils.isEmpty(email)
                || StringUtils.isEmpty(password)
                || StringUtils.isEmpty(confirmPassword)) {
            throw new BusinessException("数据不能为空!!!");
        }
        //1.2.两次密码是否相同
        if (!password.equals(confirmPassword)) {
            throw new BusinessException("两次密码不一致!!!");
        }
        //4.是否曾经入驻过
        User user1 = userMapper.loadByEmail(email);
        if(user1 != null){
            throw new BusinessException("该邮箱已经注册，请直接登录。忘记密码请联系管理员!!!");
        }
        //2.保存数据
        //2.1.先保存t_logininfo
        User user = emailuserDto2User(userDto);
        Logininfo logininfo = emailuser2Logininfo(user);
        logininfoMapper.save(logininfo);//自增
        //2.2.再保存t_user
        user.setLogininfoId(logininfo.getId());
        userMapper.save(user);

        //3.发送邮件：审核通过邮件 - 叫他激活
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
        //设置发送方
        helper.setFrom("306243239@qq.com");
        //设置主题
        helper.setSubject("账号激活邮件");
        //设置内容
        helper.setText("<h1>你的邮箱账号已经注册!!!</h1>" +
                "<a href='http://localhost:8080/user/email/active/"+logininfo.getId()+"'>点击该链接激活使用</a>",true);
        //设置收件人
        helper.setTo(email);
        //发送
        javaMailSender.send(mimeMessage);

    }
    /**
     * 用户手机注册-转换对象user
     *
     */
    private User userDto2User(UserDto userDto) {
        User user = new User();
        //设置user
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //密码加密
        String md5psw = MD5Utils.encrypByMd5(userDto.getPwd() + salt);
        user.setPassword(md5psw);
        return user;
    }
    /**
     * 用户邮箱注册-转换对象user
     *
     */
    private User emailuserDto2User(UserDto userDto) {
        User user = new User();
        //设置user
        user.setUsername(userDto.getEmail());
        user.setEmail(userDto.getEmail());
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //密码加密
        String md5psw = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5psw);
        //设置用户表禁用，发送邮件激活后再启用
        //user.setState(0);
        return user;
    }

    /**
     * 用户手机注册-转换对象logininfo
     *
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //复制对象 相同字段名赋值
        BeanUtils.copyProperties(user,logininfo);
        //设置类型是管理员
        logininfo.setType(1);
        return logininfo;
    }

    /**
     * 用户邮箱注册-转换对象logininfo
     *
     */
    private Logininfo emailuser2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        //复制对象 相同字段名赋值
        BeanUtils.copyProperties(user,logininfo);
        //设置类型是管理员
        logininfo.setType(1);
        //设置登录信息表禁用，发送邮件激活后再启用
        logininfo.setDisable(false);
        return logininfo;
    }


    /**
     * 重写save方法，关联logininfo表
     * @param user
     */
    @Override
    @Transactional
    public void save(User user) {
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //密码加密
        String md5psw = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setPassword(md5psw);
        //复制user对象字段内容到logininfo里面
        Logininfo logininfo = user2Logininfo(user);
        //先保存logininfo，返回自增长ID。
        logininfoMapper.save(logininfo);
        //设置user的LogininfoId
        user.setLogininfoId(logininfo.getId());
        super.save(user);
    }

    /**
     * 重写remove方法，关联logininfo表
     * @param id
     */
    @Override
    @Transactional
    public void remove(Long id) {
        User user = userMapper.loadById(id);
        //通过employee的get方法获取logininfo的id来同步删除数据
        logininfoMapper.remove(user.getLogininfoId());
        super.remove(id);
    }

    /**
     * 重写update方法，关联logininfo表
     * @param user
     */
    @Override
    @Transactional
    public void update(User user) {
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //密码加密
        String md5psw = MD5Utils.encrypByMd5(user.getPassword() + salt);
        user.setPassword(md5psw);
        //复制user对象字段内容到logininfo里面
        Logininfo logininfo = user2Logininfo(user);
        //通过user查询数据库获取logininfo_id
        Long logininfo_id = userMapper.loadById(user.getId()).getLogininfoId();
        //设置logininfo的logininfo_id
        logininfo.setId(logininfo_id);
        //同步修改logininfo
        logininfoMapper.update(logininfo);
        super.update(user);
    }
}
